﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Timers;
using TweetSharp.Twitter.Extensions;
using TweetSharp.Twitter.Fluent;
using TweetSharp.Twitter.Model;

namespace Halfwit.Pollers
{
    public abstract class TwitterPoller
    {
        public TwitterPoller(Action<TwitterPoller, TwitterResult> callback, Func<byte> getRefreshInterval)
        {
            Description = "Timeline";

            _getInterval = getRefreshInterval;
            _callback = callback;

            _timer = new Timer { Enabled = false };
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);

            //System.Diagnostics.Trace.WriteLine(this.GetType().Name + " initialized");
        }

        public TwitterPoller(Action<TwitterPoller, TwitterResult> callback)
            : this(callback, () => Properties.Settings.Default.RefreshInterval)
        {
        }

        //~TwitterPoller()
        //{
        //    System.Diagnostics.Trace.WriteLine(this.GetType().Name + " finalized");
        //}

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Poll();
        }

        void RequestComplete(object sender, TwitterResult result, object userState)
        {
            if (App.Current.Dispatcher != Dispatcher.CurrentDispatcher)
            {
                App.Current.Dispatcher.Invoke(new Action<object, TwitterResult, object>(RequestComplete), sender, result, null);
                return;
            }

            if (!(result.IsFailWhale || result.IsNetworkError || result.IsTwitterError))
            {
                OnSuccessfulRequest(result);
            }
            _callback(this, result);
        }

        private Func<byte> _getInterval;
        private Timer _timer;
        private Action<TwitterPoller, TwitterResult> _callback;

        protected abstract ITwitterLeafNode CreateRequest(IFluentTwitter twitter);
        protected abstract void OnSuccessfulRequest(TwitterResult result);

        public void Reset()
        {
            LastId = null;
        }

        protected long? LastId { get; set; }

        protected virtual bool CanPoll()
        {
            return true;
        }

        public string Description { get; protected set; }

        public bool IsActive
        {
            get { return _timer.Enabled; }
            set
            {
                _timer.Enabled = value;
                //System.Diagnostics.Trace.WriteLine(GetType().Name + " Timer.Enabled = " + _timer.Enabled);
            }
        }

        public bool Poll()
        {
            if (!CanPoll()) return false;

            _timer.Stop();

            CreateRequest(TwitterConnection.CreateRequest()).CallbackTo(RequestComplete).BeginRequest();

            //var request = CreateRequest(TwitterConnection.CreateRequest());
            //request.RequestAsyncSafe(RequestComplete);

            _timer.Interval = _getInterval() * 60 * 1000;
            _timer.Start();

            return true;
        }

        public virtual IEnumerable<TwitterStatus> ToStatuses(TwitterResult result)
        {
            return result.AsStatuses();
        }
    }
}
